package com.bdi.mqtt_broker.mqtt_protocol;

import com.bdi.mqtt_broker.constant.Constants;
import com.bdi.mqtt_broker.model.SessionStore;
import com.bdi.mqtt_broker.service.ISessionStoreService;
import com.bdi.mqtt_broker.service.ISubscribeStoreService;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @author WangNing yogehaoren@gmial.com <br>
 * @since 1.0
 * MQTT 客户端 主动断开连接
 */
@Slf4j
public class DisConnect {

    private final ISessionStoreService sessionStoreService;

    private final ISubscribeStoreService subscribeStoreService;

    public DisConnect(ISessionStoreService sessionStoreService, ISubscribeStoreService subscribeStoreService){
        this.subscribeStoreService = subscribeStoreService;
        this.sessionStoreService = sessionStoreService;
    }

    public void processDisConnect(Channel channel, MqttMessage msg) {
        String clientId = (String) channel.attr(AttributeKey.valueOf(Constants.CHANNEL_ATTRIBUTE_CLIENT_ID)).get();
        SessionStore sessionStore = sessionStoreService.get(clientId);
        if (sessionStore != null ) {
            subscribeStoreService.removeForClient(clientId);
        }
        log.debug("DISCONNECT - clientId: {}", clientId);
        sessionStoreService.remove(clientId);
        channel.close();
    }

}
